package models

import (
	"gintest/database"
	"time"
)

type Store struct{
	Id int `json:"id" gorm:"column:id;primary_key" form:"id"`
	ClassId int `json:"class_id" gorm:"column:class_id" form:"class_id"`
	Title string `json:"title" gorm:"column:title" form:"title"`
	Logo  string `json:"logo" gorm:"column:logo" form:"logo"`
	Address string `json:"address" gorm:"column:address" form:"address"`
	City string `json:"city" gorm:"column:city" form:"city"`
	Province string `json:"province" gorm:"column:province" form:"province"`
	Introduce string `json:"introduce" gorm:"column:introduce" form:"introduce"`
	Longitude string `json:"longitude" gorm:"column:longitude" form:"longitude"`
	Latitude string `json:"latitude" gorm:"column:latitude" form:"latitude"`
	Status int `json:"status" gorm:"column:status" form:"status"`
	CreateAt time.Time  `json:"create_at" gorm:"column:create_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"create_at"`
	UpdateAt time.Time  `json:"update_at" gorm:"column:update_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"update_at"`
	DeleteAt time.Time  `json:"delete_at" gorm:"column:delete_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"delete_at"`

	StoreClass  StoreClass `json:"store_class" gorm:"ForeignKey:ClassId;AssociationForeignKey:Id"`
}
func (Store) TableName() string {
	return "store"
}

func GetStoreList(page uint64,pagesize uint64,keyword string,status uint64)(data []Store,total uint64){
	var offset=(page-1)*pagesize
	db:=database.SqlDB.Model(Store{})

	if len(keyword)!=0{
		db=db.Where("concat(id,title) like ?","%"+keyword+"%")
	}
	if status!=0 {
		db=db.Where("status=?",status)
	}
	db=db.Where("delete_at = 0 or delete_at is null")

	db.Preload("StoreClass").Offset(offset).Limit(pagesize).Order("id desc").Find(&data)

	db.Model(Store{}).Count(&total)
	return data,total
}

func AddStore(data *Store) error{
	if data.UpdateAt.IsZero(){
		data.UpdateAt=time.Now()
	}
	if data.CreateAt.IsZero(){
		data.CreateAt=time.Now()
	}
	return database.SqlDB.Model(Store{}).Omit("StoreClass").Create(data).Error
}
func DelStoreByIds(ids []int) error{
	//return database.SqlDB.Model(User{}).Where("id in (?)",ids).Delete(User{}).Error
	return database.SqlDB.Model(Store{}).Where("id in (?) and (delete_at = 0 or delete_at is null)",ids).Update("delete_at",time.Now().Local().String()).Error
}
func GetStoreById(id int) (data Store){
	database.SqlDB.Model(Store{}).Preload("StoreClass").Where("id=?",id).First(&data);
	return data
}
func EditStoreById(id int,data interface{}) error{
	//update_at不存在，填充当前时间
	if _, has := data.(map[string]interface{})["update_at"]; !has {
		data.(map[string]interface{})["update_at"]=time.Now()
	}
	return database.SqlDB.Model(&Store{}).Where("id=?",id).Updates(data).Error
}
